/*
 * These files are distributed under the terms of the GNU GPLv2, the GNU General
 * Public version 2. See LICENSE.txt
 */
package fileCommodore.plugin.usermenu;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class EditorPanel extends JPanel
{
	private JButton edit = new JButton("Edit");
	private JButton neww = new JButton("New");
	private JButton del = new JButton("Delete");
	private JButton up = new JButton("Up");
	private JButton down = new JButton("Down");
	private JPanel buttons = new JPanel(new GridLayout(1, 5));
	
	private EntryListModel model;
	private JList list = new JList();
	private JScrollPane listPane = new JScrollPane(list);
	
	private JDialog owner;
	
	public EditorPanel(JDialog owner, EntryListModel model)
	{
		this.model = model;
		this.owner = owner;
		
		setLayout(new BorderLayout());
		
		buttons.add(edit);
		buttons.add(neww);
		buttons.add(del);
		buttons.add(up);
		buttons.add(down);
		add(buttons, BorderLayout.NORTH);
		
		list.setModel(model);
		add(listPane, BorderLayout.CENTER);

		edit.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				handleEdit();
			}
		});

		neww.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				handleNew();
			}
		});
		
		del.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				handleDelete();
			}
		});
		
		up.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				handleUp();
			}
		});
		
		down.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				handleDown();
			}
		});
	}
	
	private void handleNew()
	{
		Entry e = new Entry();
		EntryEditor ee = new EntryEditor(owner, e);
		if( ee.shouldSave() )
		{
			model.add(e);
		}
	}
	
	private void handleEdit()
	{
		if( null != list.getSelectedValue() )
		{
			Entry e = (Entry) list.getSelectedValue();
			EntryEditor ee = new EntryEditor(owner, e);
			if( ee.shouldSave() )
			{
				model.notifyListeners();
			}
		}
	}
	
	private void handleDelete()
	{
		if( null != list.getSelectedValue() )
		{
			Entry e = (Entry) list.getSelectedValue();
			model.remove(e);
		}
	}
	
	private void handleUp()
	{
		if( null != list.getSelectedValue() )
		{
			Entry e = (Entry) list.getSelectedValue();
			model.up(e);
			list.setSelectedValue(e, true);
		}
	}
	
	private void handleDown()
	{
		if( null != list.getSelectedValue() )
		{
			Entry e = (Entry) list.getSelectedValue();
			model.down(e);
			list.setSelectedValue(e, true);
		}
	}
}
